let self;
let timer;
let linking = false;
function linkHeart(succb,failcb){
    console.log("link");
    linking = true;
    wx.openBluetoothAdapter({
        success: function (res) {
            searchBlue();
            succb(res)
        },fail(res){
            failcb(res)
        }
    })
    wx.onBluetoothAdapterStateChange(function(res) {
        var available = res.available;
        var discovering = res.discovering;
        console.log(`adapterState changed, now is`, res)
    })
}

function searchBlue(){
    wx.startBluetoothDevicesDiscovery({
    services:['0000180d-0000-1000-8000-00805f9b34fb'
    // ,'0000180a-0000-1000-8000-00805f9b34fb'
    ],
    success:function(res){
        console.log("discovering success",res);
    },fail:function(res){
        console.log("discovering fail",res);
    }})
    setTimeout(function(){ 
        console.log("已找到设备 停止搜索");
        wx.stopBluetoothDevicesDiscovery({
            success: function(res){
            }
        })
    },30*1000)
}
function foundBlue(self,fuc){
    self = self;
    wx.onBluetoothDeviceFound(function(devices){
        fuc(devices);
        console.log('找到新设备',devices)
    })
}
function stateListener(self){
    wx.onBLEConnectionStateChange(function(res) {
        if(!res.connected){
            console.log('设备断开 正在重连')
            setTimeout(function(){ 
                connectblue(self);
            },500);
            // closeblue(self,deviceId);
            // wx.showToast({
            //     title: '设备已断开',
            //     icon: 'success',
            //     duration: 2000
            // })
        }
        console.log("状态监听",res);
    })
}
let setHeartCall;
function connectblue(self,call){
    let deviceId = self.data.deviceId;
    setHeartCall = call;
    wx.createBLEConnection({
        deviceId: deviceId,
        success: function (res) {
            console.log("createBLEConnection success",res)
                wx.getBLEDeviceServices({
                deviceId: deviceId,
                success: function (res) {
                    console.log('获取服务成功', res)
                    getBLEDevice(res.services,deviceId,call)
                },fail:function(res){
                    console.log('获取服务失败', res)
                }
            })
        }
    })
}
function getBLEDevice(services,deviceId,call){
        let servicesId;
        if(getApp().globalData.isIOS)servicesId = services[0].uuid;
        else servicesId = services[3].uuid;
        // let servicesId = "0000180d-0000-1000-8000-00805f9b34fb"
        wx.getBLEDeviceCharacteristics({
            deviceId: deviceId,
            serviceId: servicesId,
            success: function (cres) {
                console.log('特征值 成功', cres)
                let cId = cres.characteristics[0].uuid;
                // let cId = "00002a37-0000-1000-8000-00805f9b34fb";
                notify(deviceId,servicesId,cId,call);
            },fail:function(res){
                console.log('特征值 失败:', res)
            }
        })
}
function notify(deviceId,serviceId,cId,setHeartCall){
    console.log("deviceId:",deviceId);
    console.log("serviceId:",serviceId);
    console.log("cId:",cId);
    let did = deviceId;
    // timer= setInterval(function(){
    //     wx.readBLECharacteristicValue({
    //         deviceId: deviceId,
    //         serviceId: serviceId,
    //         characteristicId: cId,
    //         success: function (res) {
    //         },fail:function(res){
    //         }
    //     })
    // },5000)
    wx.notifyBLECharacteristicValueChange({
        state: true, 
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: cId,
        success: function (res) {
            console.log('notify success', res)
        },fail:function(){
            console.log('notify fail', res)
        }
    })
    wx.onBLECharacteristicValueChange(function(res) {
        let heartrate= arrayBufferToStr(res.value)
        if(setHeartCall)setHeartCall(heartrate);
        console.log(res.characteristicId+'收到蓝牙通知 :',heartrate);
    })
}
function arrayBufferToStr(buffer){
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(10)).slice(-2)).join('');
}
function stopSearch(){
    wx.stopBluetoothDevicesDiscovery({
        success: function(res){
        }
    })
}
function closeblue(self,deviceId){
    clearInterval(timer)
    wx.stopBluetoothDevicesDiscovery({
        success: function(res){
        }
    })
    wx.closeBLEConnection({
        deviceId:deviceId||self.data.deviceId,
        success:function(){
            console.log("关闭蓝牙连接")
        }
    });
    wx.closeBluetoothAdapter({
            success: function (res) {
            console.log("关闭蓝牙适配器",res)
        }
    })
    self.setData({
        linking:false,
        linked:false,
        linkstate:"连接心率带"
    })
}
module.exports={
    linkHeart:linkHeart,
    searchBlue:searchBlue,
    foundBlue:foundBlue,
    connectblue:connectblue,
    closeblue:closeblue,
    stateListener:stateListener,
    stopSearch:stopSearch
}